<?php

namespace app\api\controller;

use app\facade\Redis;
use app\models\{PlatClass, RecpeopleLeimu, RecpeopleCommu, BussinessLog, Business, PlatSons, AgentCommu, Goods, GoodsSpec, Region,  Order, OrderGoods, Coupon,  Order as Orders};
use think\Facade\Config as Configs;
use EasyWeChat\Factory;
use think\Validate;
use think\Db;
use think\facade\Log;

class Peoples extends Base
{

    protected $middleware = ['Pauth'];

    public function catelist()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'yxlist' => 'require'
            ], [
                'yxlist.require' => '服务内容不能为空'
            ]);
            if (!$validate->check($data)) {
                $this->result([], 1, $validate->getError());
            }
            $people = $this->request->people;
            Db::startTrans();
            try {
                (new RecpeopleLeimu())->where(['peopleid' => $people['id']])->delete();
                foreach ($data['yxlist'] as $xq) {
                    (new RecpeopleLeimu())->allowfield(true)->save(['peopleid' => $people['id'], 'leimuid' => $xq['id']]);
                }
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                $this->result([], 1, '操作失败，请重试');
            }
            $this->result([], 0, '操作成功');
        }
    }

    public function commulist()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'id' => 'require',
                'type' => 'require|in:1,2', //1删除 2申请
            ], [
                'id.require' => 'ID不能为空',
                'type.require' => 'type不能为空',
                'type.in' => 'type类型不正确',
            ]);
            if (!$validate->check($data)) {
                $this->result([], 1, $validate->getError());
            }
            if ($data['type'] == 2) {
                $bcommu = (new RecpeopleCommu())->where(['peopleid' => $this->request->people['id'], 'commuid' => $data['id']])->find();
                if (!empty($bcommu) && ($bcommu['status'] == 1 || $bcommu['status'] == 2)) {
                    $this->result([], 1, '已服务或申请中小区不可重复申请');
                }
            }
            Db::startTrans();
            try {
                if ($data['type'] == 1) {
                    (new RecpeopleCommu())->where(['peopleid' => $this->request->people['id'], 'id' => $data['id']])->delete();
                }
                if (!empty($bcommu)) {
                    (new RecpeopleCommu())->where(['peopleid' => $this->request->people['id'], 'commuid' => $data['id']])->update(['status' => 2]);
                } else {
                    (new RecpeopleCommu())->allowfield(true)->save(['peopleid' => $this->request->people['id'], 'commuid' => $data['id'], 'status' => 2]);
                }
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                $this->result([], 1, '操作失败，请重试');
            }
            $this->result([], 0, '操作成功');
        } else {
            $type = $this->request->get('type/d', 1);
            $lat = $this->request->get('lat/d', 0);
            $lon = $this->request->get('lon/d', 0);
            $filed = 'ROUND(6378.138*2*ASIN(SQRT(POW(SIN((' . $lat . '*PI()/180-lat*PI()/180)/2),2)+COS(' . $lat . '*PI()/180)*COS(lat*PI()/180)*POW(SIN((' . $lon . '*PI()/180-lon*PI()/180)/2),2)))*100)/100 AS dist';
            if ($type == 1) {
                $list = (new RecpeopleCommu())->where(['peopleid' => $this->request->people['id']])->select();
                $result = [];
                foreach ($list as $row) {
                    $commu = (new AgentCommu())->field('id,name,address,' . $filed)
                        ->where('id', $row['commuid'])->find();
                    if (!empty($commu)) {
                        $result[] = [
                            'id' => $row['id'] ?? '',
                            'commuid' => $commu['id'] ?? '',
                            'status' => $row['status'] ?? '',
                            'name' => $commu['name'] ?? '',
                            'address' => $commu['address'] ?? '',
                            'dist' => $commu['dist'] ?? '',
                        ];
                    }
                }
            } else {
                $result = (new AgentCommu())
                    ->field('id,name,address,' . $filed)
                    ->limit(15)
                    ->order('dist asc')
                    ->where('status', 1)
                    ->select();
                foreach ($result as $row) {
                    $list = (new RecpeopleCommu())->where(['peopleid' => $this->request->people['id'], 'commuid' => $row['id']])->find();
                    if (empty($list)) {
                        $row['status'] = 0;
                    } else {
                        $row['status'] = $list['status'];
                    }
                }
            }

            $this->result($result, 0, '查询完成');
        }
    }

    public function moneylog()
    {
        $list = (new BussinessLog())->order('id desc');
        $list = $list->where(['user_id' =>  $this->request->shop['id']])
            ->field('info,money,created')
            ->paginate(20, false, ['query' => $this->request->param()]);
        $this->result($list, 0, '查询完成');
    }

    public function people_edit()
    {
        if ($this->request->isPost()) {
        } else {
            $people = $this->request->people;
            $leimu = (new RecpeopleLeimu())->where(['peopleid' => $people['id']])->column('leimuid') ?? [];
            $leimulist = [];
            foreach ($leimu as $lemu) {
                $PlatSons = (new PlatSons())->where(['id' => $lemu])->find();
                if (!empty($PlatSons)) {
                    $leimulist[] = [
                        'id' => $PlatSons['id'],
                        'name' => $PlatSons['name'],
                    ];
                }
            }

            $datas = [
                'money' => $people['money'] ?? 0,
                'leimu' => $leimulist,
                'todyacount' => (new Orders())->whereTime('paytimes', '>=', date('Y-m-d'))->where(['putorder' => $people['id'], 'status' => [2, 3, 4]])->count(),
                'todytotal' => (new Orders())->whereTime('paytimes', '>=', date('Y-m-d'))->where(['putorder' => $people['id'], 'status' => [2, 3, 4]])->sum('total'),
                'yesacount' => (new Orders())->whereTime('paytimes', '<', date('Y-m-d'))->whereTime('paytimes', '>=', date('Y-m-d', time() - 86400))->where(['putorder' => $people['id'], 'status' => [2, 3, 4]])->count(),
                'yestotal' => (new Orders())->whereTime('paytimes', '<', date('Y-m-d'))->whereTime('paytimes', '>=', date('Y-m-d', time() - 86400))->where(['putorder' => $people['id'], 'status' => [2, 3, 4]])->sum('total'),
                'order' => (new Orders())->where(['putorder' => $people['id'], 'status' => [2, 3, 4]])->count(),
                'total' => (new Orders())->where(['putorder' => $people['id'], 'status' => [2, 3, 4]])->sum('total'),
            ];
            $this->result($datas, 0, '获取成功');
        }
    }


    public function orderstatus()
    {
        $data = $this->request->post();
        $validate = new Validate([
            'id' => 'require',
            'status' => 'require|in:3,4,5'
        ], [
            'id.require' => '订单ID不能为空',
            'status.require' => '状态不能为空',
            'status.in' => '状态不正确',
        ]);
        if (!$validate->check($data)) {
            $this->result([], 1, $validate->getError());
        }
        $order = (new Order())->where(['id' => $data['id']])->find();
        if (empty($order)) {
            $this->result([], 1, '订单不存在');
        }
        $people =  $this->request->people;
        switch ($data['status']) {
            case '3':
                if ($order['status'] != 2) {
                    $this->result([], 1, '订单状态不可接单');
                }
                $commuid = (new RecpeopleCommu())->where(['peopleid' => $people['id'], 'status' => 1])->column('commuid') ?? [];
                $leimu = (new RecpeopleLeimu())->where(['peopleid' => $people['id']])->column('leimuid') ?? [];
                if (!in_array($order['leimu'], $leimu)) {
                    $this->result([], 1, '无当前类目接单权限');
                }
                if (!in_array($order['xiaoquid'], $commuid)) {
                    $this->result([], 1, '无当前小区接单权限');
                }
                //完成订单
                $res = (new Order())->where('id', $data['id'])->update(['putorder' => $people['id'], 'status' => $data['status'], 'fwtimes' => date('Y-m-d H:i:s')]);
                if ($res) {
                    $this->result([], 0, '操作成功');
                }

                $this->result([], 1, '操作失败，请重试');
                break;
            case '4':
                if ($order['status'] != 3) {
                    $this->result([], 1, '订单状态不可确认服务');
                }
                //完成订单
                $res = (new Order())->where('id', $data['id'])->update(['putstatus' => 2, 'puttime' => date('Y-m-d H:i:s')]);
                if ($res) {
                    $this->result([], 0, '操作成功');
                }
                $this->result([], 1, '操作失败，请重试');
                break;
            case '5':
                if ($order['status'] != 3) {
                    $this->result([], 1, '订单状态不可取消接单');
                }
                //取消
                Db::startTrans();
                try {
                    (new Order())->where('id', $data['id'])->update([
                        'status' => 2,
                        'putstatus' => 1
                    ]);
                    Db::commit();
                } catch (\Exception $e) {
                    dump($e->getMessage());
                    Db::rollback();
                    $this->result([], 1, '操作失败，请重试');
                }
                $this->result([], 0, '操作成功');
                break;
            default:
                $this->result([], 1, '状态出错');
                break;
        }
    }

    public function orderdetail()
    {
        $id = $this->request->get('id/d', 0);
        $list = (new Order())->where('id', $id)->field('putorder,coupon,paytimes,fwtimes,finishtimes,caceltimes', true)->find();
        if ($list) {
            $list['images'] = json_decode($list['images'] ?? '', true) ?? [];
            $list['leimu_name'] = (new PlatSons())->where('id', $list['leimu'])->value('name') ?? '';
            $list['xiaoquaddress'] = (new AgentCommu())->where('id', $list['xiaoquid'])->value('address') ?? '';
            $list['status_text'] = $list->status_text;
            $list['province_text'] = (new Region())->where(['area_code' => $list['province']])->value('name');
            $list['city_text'] = (new Region())->where(['area_code' => $list['city']])->value('name');
            $list['area_text'] = (new Region())->where(['area_code' => $list['area']])->value('name');
            $list['street_text'] = (new Region())->where(['id' => $list['street']])->value('name');
            $goods = (new OrderGoods())->where('ordersn', $list['ordersn'])->field('id,ordersn,images,number,title,name,goodsid,goodspecid,price,unmit,iscompent')->select();
            foreach ($goods as $good) {
                $good['images'] = json_decode($good['images'], true);
            }
            $list['good'] = $goods;
        }
        $this->result($list, 0, '获取成功');
    }

    public function orderlist()
    {
        $status = $this->request->get('status/d', 0);
        $list = (new Order())->order('id desc');
        $people = $this->request->people;
        $list = $list->where('status', $status);
        switch ($status) {
            //待接单
            case '2':
                //获取小区数据
                $commuid = (new RecpeopleCommu())->where(['peopleid' => $people['id'], 'status' => 1])->column('commuid') ?? [];
                $leimu = (new RecpeopleLeimu())->where(['peopleid' => $people['id']])->column('leimuid') ?? [];
                $list = $list->where(['xiaoquid' => $commuid, 'leimu' => $leimu, 'ordertype' => [1, 3]]);
                $list = $list->where('status', $status);
                break;
            default:
                $list = $list->where('putorder', $people['id']);
                break;
        }
        $list = $list->field('id,leimu,putorder,putstatus,images,xiaoquid,putaddress,sendaddress,qusong,types,ordertype,ordersn,businessid,status,total,ptotal,shouhou,tuikuan,created,ispj,payment')->paginate(20, false, ['query' => $this->request->param()]);
        foreach ($list as $lists) {
            $lists['tnumber'] = 0;
            $ordergoods = (new OrderGoods())->where(['ordersn' => $lists['ordersn']])->field('id,title,name,unmit,goodspecid,images,number,iscompent,price')->select();
            foreach ($ordergoods as $goods) {
                $lists['tnumber'] += $goods['number'];
                $goods['images'] = json_decode($goods['images'] ?? '', true);
            }
            $lists['goods'] = $ordergoods;
            $lists['status_text'] = $lists->status_text;
            $lists['images'] = json_decode($lists['images'], true) ?? [];
            $lists['leimu_name'] = (new PlatSons())->where('id', $lists['leimu'])->value('name') ?? '';
            $lists['xiaoquaddress'] = (new AgentCommu())->where('id', $lists['xiaoquid'])->value('address') ?? '';
        }
        $this->result($list, 0, '获取成功');
    }
}
